/*
 * @Description: 
 * @Version: 2.0
 * @Autor: Seven
 * @Date: 2025-04-01 10:33:04
 * @LastEditors: Seven
 * @LastEditTime: 2025-04-22 15:07:31
 */
// 示例飞机轨迹数据（经纬度、高度、时间戳）
import * as Cesium from "cesium";
export const flightData = {
    plane1: {
        positions: [
            { lon: 116.39, lat: 39.90, alt: 10000, time: "2023-10-01T00:00:00Z" },
            { lon: 116.50, lat: 40.00, alt: 10500, time: "2023-10-01T00:10:00Z" },
            { lon: 116.60, lat: 40.10, alt: 11000, time: "2023-10-01T00:20:00Z" }
        ],
        linePlaneColor: '#FF0000',
        modelUri: "./models/Cesium_Air.glb" // 飞机模型路径
    },
    plane2: {
        positions: [
            { lon: 115.39, lat: 38.90, alt: 9000, time: "2023-10-01T00:00:00Z" },
            { lon: 115.50, lat: 39.00, alt: 9500, time: "2023-10-01T00:10:00Z" },
            { lon: 115.60, lat: 39.10, alt: 10000, time: "2023-10-01T00:20:00Z" }
        ],
        linePlaneColor: '#FFFF00',
        modelUri: "./models/Cesium_Air.glb" // 飞机模型路径
    },
};
// 创建扇环几何体
export function createAnnularSector(centerLonLat, innerRadius, outerRadius, startAngle, endAngle) {
    const positions = [];
    const centerLon = centerLonLat[0];
    const centerLat = centerLonLat[1];

    // 将中心点转换为 Cartographic 坐标（弧度）
    const centerCartographic = Cesium.Cartographic.fromDegrees(centerLon, centerLat);
    const R = Cesium.Ellipsoid.WGS84.maximumRadius; // 地球最大半径

    // 生成外圆弧顶点（顺时针方向）
    for (let angle = startAngle; angle <= endAngle; angle += 1) {
        const theta = Cesium.Math.toRadians(angle);
        // 计算东-北平面偏移量
        const dx = outerRadius * Math.cos(theta); // 东方向分量
        const dy = outerRadius * Math.sin(theta); // 北方向分量

        // 转换为经纬度增量（弧度 → 度）
        const deltaLon = (dx / (R * Math.cos(centerCartographic.latitude))) * (180 / Math.PI);
        const deltaLat = (dy / R) * (180 / Math.PI);

        // 计算顶点坐标
        const pointCartesian = Cesium.Cartesian3.fromDegrees(
            centerLon + deltaLon,
            centerLat + deltaLat
        );
        positions.push(pointCartesian);
    }

    // 生成内圆弧顶点（逆时针方向，保持闭合）
    for (let angle = endAngle; angle >= startAngle; angle -= 1) {
        const theta = Cesium.Math.toRadians(angle);
        const dx = innerRadius * Math.cos(theta);
        const dy = innerRadius * Math.sin(theta);

        const deltaLon = (dx / (R * Math.cos(centerCartographic.latitude))) * (180 / Math.PI);
        const deltaLat = (dy / R) * (180 / Math.PI);

        const pointCartesian = Cesium.Cartesian3.fromDegrees(
            centerLon + deltaLon,
            centerLat + deltaLat
        );
        positions.push(pointCartesian);
    }

    // 闭合多边形（连接首尾点）
    positions.push(positions[0].clone());
    return positions;
}
// 添加扇环网格线（径向线 + 同心圆弧）
export function addSectorGrid(viewer, centerLonLat, innerRadius, outerRadius, startAngle, endAngle) {
    const centerLon = centerLonLat[0];
    const centerLat = centerLonLat[1];
    const R = Cesium.Ellipsoid.WGS84.maximumRadius;
    const centerCarto = Cesium.Cartographic.fromDegrees(centerLon, centerLat);

    // 生成径向线（每隔6.4度一条）
    const angleStep = 6.4; // 角度间隔
    // 生成径向线（从内环到外环）
    for (let angle = startAngle; angle <= endAngle; angle += angleStep) {
        const theta = Cesium.Math.toRadians(angle);

        // 计算内环端点
        const dxInner = innerRadius * Math.cos(theta);
        const dyInner = innerRadius * Math.sin(theta);
        const deltaLonInner = (dxInner / (R * Math.cos(centerCarto.latitude))) * (180 / Math.PI);
        const deltaLatInner = (dyInner / R) * (180 / Math.PI);
        const innerPoint = Cesium.Cartesian3.fromDegrees(
            centerLon + deltaLonInner,
            centerLat + deltaLatInner
        );

        // 计算外环端点
        const dxOuter = outerRadius * Math.cos(theta);
        const dyOuter = outerRadius * Math.sin(theta);
        const deltaLonOuter = (dxOuter / (R * Math.cos(centerCarto.latitude))) * (180 / Math.PI);
        const deltaLatOuter = (dyOuter / R) * (180 / Math.PI);
        const outerPoint = Cesium.Cartesian3.fromDegrees(
            centerLon + deltaLonOuter,
            centerLat + deltaLatOuter
        );

        // 绘制内环到外环的径向线
        viewer.entities.add({
            polyline: {
                positions: [innerPoint, outerPoint],
                width: 1,
                material: new Cesium.PolylineDashMaterialProperty({
                    color: Cesium.Color.GRAY.withAlpha(0.4),
                    dashLength: 40
                })
            }
        });
        // 在径向线外环端点添加角度标签
        viewer.entities.add({
            position: outerPoint,
            label: {
                text: `${angle.toFixed(1)}°`, // 显示角度值（保留1位小数）
                font: "14px sans-serif",
                fillColor: Cesium.Color.WHITE,
                backgroundColor: Cesium.Color.BLACK.withAlpha(0),
                pixelOffset: new Cesium.Cartesian2(20, 0), // 向右偏移10像素
                showBackground: true,
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000000), // 50公里内可见
                disableDepthTestDistance: Number.POSITIVE_INFINITY, // 始终显示在最前
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND // 贴地显示（若需要）

            }
        });
    }

    // 生成同心圆弧线（每100000米一条）
    const radiusStep = 100000; // 半径间隔
    // 在 addSectorGrid 函数的同心圆弧生成部分添加标签
    for (let r = innerRadius; r <= outerRadius; r += radiusStep) {
        const arcPoints = [];
        // const thetaStart = Cesium.Math.toRadians(startAngle);
        // const thetaEnd = Cesium.Math.toRadians(endAngle);


        //将角度（degrees）转换为弧度（radians）许多坐标转换和几何计算（如经纬度转笛卡尔坐标、球面三角计算等）需要以弧度为单位的角度值
        // 生成圆弧顶点（保持原有逻辑）
        for (let angle = startAngle; angle <= endAngle; angle += 1) {
            const theta = Cesium.Math.toRadians(angle);
            const dx = r * Math.cos(theta);
            const dy = r * Math.sin(theta);
            const deltaLon = (dx / (R * Math.cos(centerCarto.latitude))) * (180 / Math.PI);
            const deltaLat = (dy / R) * (180 / Math.PI);
            const point = Cesium.Cartesian3.fromDegrees(centerLon + deltaLon, centerLat + deltaLat);
            arcPoints.push(point);
        }

        // 强制添加 endAngle 的闭合点
        if (endAngle > startAngle) {
            const theta = Cesium.Math.toRadians(endAngle);
            const dx = r * Math.cos(theta);
            const dy = r * Math.sin(theta);
            const deltaLon = (dx / (R * Math.cos(centerCarto.latitude))) * (180 / Math.PI);
            const deltaLat = (dy / R) * (180 / Math.PI);
            const endPoint = Cesium.Cartesian3.fromDegrees(
                centerLon + deltaLon,
                centerLat + deltaLat
            );
            arcPoints.push(endPoint);
        }

        // 添加圆弧线实体（保持原有逻辑）
        viewer.entities.add({
            polyline: {
                positions: arcPoints,
                width: 1,
                material: Cesium.Color.LIGHTGRAY.withAlpha(0.5),
                clampToGround: true
            }
        });

        // **新增：添加起始和结束端点的标签**
        // 获取起始点和结束点
        const startPoint = arcPoints[0];
        const endPoint = arcPoints[arcPoints.length - 1];

        // 添加起始点标签（显示半径）
        viewer.entities.add({
            position: startPoint,
            label: {
                text: r.toString() + 'm', // 显示当前半径值
                font: '14px sans-serif',
                fillColor: Cesium.Color.WHITE,
                backgroundColor: Cesium.Color.BLACK.withAlpha(0.5),
                pixelOffset: new Cesium.Cartesian2(0, 20), // 向上偏移20像素
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000000), // 50公里内可见
                disableDepthTestDistance: Number.POSITIVE_INFINITY // 始终显示在最前
            }
        });

        // 添加结束点标签（显示半径）
        viewer.entities.add({
            position: endPoint,
            label: {
                text: r.toString() + 'm',
                font: '14px sans-serif',
                fillColor: Cesium.Color.WHITE,
                backgroundColor: Cesium.Color.BLACK.withAlpha(0.5),
                pixelOffset: new Cesium.Cartesian2(0, -20), // 向下偏移20像素
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000000),
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            }
        });
    }


    //小块中展示动态数据
    // 生成网格数据可视化
    const mockData = generateMockData(centerLonLat, innerRadius, outerRadius, startAngle, endAngle);
    visualizeGridData(viewer, mockData, centerLonLat);
}
// 新增：模拟数据生成器数据结构
function generateMockData(centerLonLat, innerRadius, outerRadius, startAngle, endAngle) {
    const data = new Map();
    const radiusStep = 100000;
    const angleStep = 6.4;

    for (let r = innerRadius; r < outerRadius; r += radiusStep) {
        for (let a = startAngle; a < endAngle; a += angleStep) {
            const value = Math.random() * 100; // 0-100随机值
            const center = computeCellCenter(centerLonLat, r, a, radiusStep, angleStep);
            data.set(`${r}_${a}`, {
                value: value,
                center: center,
                bounds: {
                    rMin: r,
                    rMax: r + radiusStep,
                    aMin: a,
                    aMax: a + angleStep
                }
            });
        }
    }
    console.log("data++++", data);

    return data;
}
// 新增：数据可视化函数
function visualizeGridData(viewer, data, centerLonLat) {
    data.forEach((value, key) => {
        // 创建文本标签
        viewer.entities.add({
            position: value.center,
            label: {
                text: value.value.toFixed(1),
                font: '14px sans-serif',
                fillColor: getColorByValue(value.value),
                pixelOffset: new Cesium.Cartesian2(0, 0),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 500000),//500公里外自动隐藏标签
                scaleByDistance: new Cesium.NearFarScalar(1e3, 1.0, 1e5, 0.3)//标签随距离动态缩放
            }
        });

        // 创建背景色块
        viewer.entities.add({
            polygon: {
                hierarchy: createCellGeometry(value.bounds, centerLonLat),
                material: getColorByValue(value.value).withAlpha(0.2),
                outline: true,
                outlineColor: Cesium.Color.BLACK.withAlpha(0.1),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
    });
}
// 新增：颜色映射函数
function getColorByValue(value) {
    const hue = (1 - value / 100) * 240; // 从蓝(0)到红(100)
    return Cesium.Color.fromHsl(hue / 360, 1.0, 0.5);
}
// 新增：创建单元格几何图形
function createCellGeometry(bounds, centerLonLat) {
    const [lon, lat] = centerLonLat;
    const R = Cesium.Ellipsoid.WGS84.maximumRadius;
    const positions = [];

    // 生成四个边界点
    const angles = [bounds.aMin, bounds.aMax];
    const radii = [bounds.rMin, bounds.rMax];

    angles.forEach(a => {
        radii.forEach(r => {
            const theta = Cesium.Math.toRadians(a);
            const dx = r * Math.cos(theta);
            const dy = r * Math.sin(theta);

            const deltaLon = (dx / (R * Math.cos(Cesium.Math.toRadians(lat)))) * (180 / Math.PI);
            const deltaLat = (dy / R) * (180 / Math.PI);

            positions.push(
                Cesium.Cartesian3.fromDegrees(
                    lon + deltaLon,
                    lat + deltaLat
                )
            );
        });
    });

    return new Cesium.PolygonHierarchy([
        positions[0], positions[1],
        positions[3], positions[2]
    ]);
}
// 新增：计算网格单元中心点
function computeCellCenter(centerLonLat, radius, angle, radiusStep, angleStep) {
    const [lon, lat] = centerLonLat;
    const R = Cesium.Ellipsoid.WGS84.maximumRadius;
    const centerRadius = radius + radiusStep / 2;
    const centerAngle = angle + angleStep / 2;

    const theta = Cesium.Math.toRadians(centerAngle);
    const dx = centerRadius * Math.cos(theta);
    const dy = centerRadius * Math.sin(theta);

    const deltaLon = (dx / (R * Math.cos(Cesium.Math.toRadians(lat)))) * (180 / Math.PI);
    const deltaLat = (dy / R) * (180 / Math.PI);

    return Cesium.Cartesian3.fromDegrees(
        lon + deltaLon,
        lat + deltaLat
    );
}